/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 */
package seedpod.webapp.view.seedpodwidgets;

import java.util.ArrayList;

import seedpod.exceptions.InvalidWidgetException;
import seedpod.exceptions.SeedpodException;
import seedpod.model.AVPair;
import seedpod.model.InstanceRelationship;
import seedpod.model.SeedpodDO;
import seedpod.model.SeedpodModel.RdbCls.FormWidget;
import seedpod.model.SeedpodModel.RdbCls.ViewWidget;
import seedpod.rdb.PMFactory;
import seedpod.rdb.PManager;
import seedpod.webapp.view.htmlwidget.Button;
import seedpod.webapp.view.htmlwidget.HiddenInput;
import seedpod.webapp.view.htmlwidget.HtmlLink;
import seedpod.webapp.view.htmlwidget.Table;

public class Object_Link extends LimsWidget {

	protected static String objectLink( SeedpodDO obj ) {
		String view = "";
		view += "<li class=\"objList\"><a href=\"instance.jsp?oid=" + obj.getOid() + "&clsName=" + obj.getMetaCls().getName() + "\">";
		view += obj.getLabel();
		view += "</a></li>";
		return view;
	}

	protected InstanceRelationship _relationship;

	protected ArrayList<Integer> _toObjOids;

	public Object_Link() {
	// TODO Auto-generated constructor stub
	}

	public Object_Link(AVPair avpair) {
		super( avpair );
	}

	@Override
	public boolean allowInPlaceEdit() {
		return false;
	}

	private String btnAddRelationship( String selectorContainer ) {
		String relationshipName = getAttribute().getName();
		String targetCls = getAttribute().getAllowedCls();
		// InstanceRelationship.getTargetClassName( getAttribute() );
		String srcCls = getAttribute().getDomainCls();

		Button btn = new Button( "addrelation_" + targetCls, "Add" );
		btn.setCssClass( "button" );
		btn.setJscript( "onClick=\"loadInstanceSelector('" + relationshipName + "', '" + targetCls + "', '" + srcCls + "', " + _relationship.getSourceOid() + ");Effect.toggle('" + selectorContainer + "', 'appear' ); return false;\"" );

		return btn.render();
	}

	// private Button btnCreateInstance() {
	// String createURL = "createInstance.jsp?clsName=" + _toClassName;
	//
	// Button btn = new Button( "createInstance", "Create" );
	// btn.setJscript( "onClick=\"document.location='" + createURL + "'\" );" );
	// btn.setCssClass( "commandButton" );
	// return btn;
	// }

	private String btnRemoveRelationship() {
		HtmlLink removeLink = new HtmlLink( "#", "[remove]" );
		removeLink.setJsCommand( "onclick=\"alert('remove' )\" " );
		removeLink.setCssClass( "actionLink" );
		return removeLink.render();
	}

	@Override
	public String doEdit() {
		return render();
	}

	@Override
	public String doView() {
		return render();
	}

	@Override
	public FormWidget getFormWidgetType() {
		return FormWidget.OBJECT_LINK;
	}

	@Override
	public ViewWidget getViewWidgetType() {
		return ViewWidget.OBJECT_LINK;
	}

	private String hiddenInputValue( String inputName, /* int index, */int inputValue ) {
		// String inputID = getAttribute().isMultiple() ? inputName + "[" + index + "]" : inputName;
		HiddenInput hiInstance = new HiddenInput( inputName, String.valueOf( inputValue ) );
		return hiInstance.render();
	}

	/**
	 * render a HTML table with lists of instances each listed by its own label
	 * 
	 * @return
	 */
	protected Table instanceTable() {
		Table instanceTable = new Table( "instanceCollection" );
		instanceTable.setAlternativeRowColor( false );
		instanceTable.setTableCellSpacing( 5, 1 );

		if ( _relationship == null || _toObjOids.size() == 0 ) setData( _avPair.getValue() );

		PManager manager;
		try {
			manager = PMFactory.getInstance().createManager();
		} catch (SeedpodException e1) {
			e1.printStackTrace();
			return null;
		}

		for ( Integer oid : _toObjOids ) {
			SeedpodDO obj = manager.createObject( getAttribute().getAllowedCls(), oid );
			if ( !obj.isPersistent() ) try {
				obj.retrieveById();
			} catch (SeedpodException e) {
				e.printStackTrace();
			}

			instanceTable.addRow();
			instanceTable.addCell( hiddenInputValue( getId(), /* i++, */oid ) );
			instanceTable.addCell( objectLink( obj ) );
			instanceTable.addCell( btnRemoveRelationship() );
		}

		return instanceTable;
	}

	/**
	 * makes a check box name = cbName[index], and with value=cbValue
	 * 
	 * @param cbName
	 * @param index
	 * @param cbValue
	 * @return rendering html for check box
	 */
	// private String objectLinkCheckBox( String cbName, int index, int cbValue ) {
	// String cbID = cbName + "[" + index + "]";
	// CheckBoxInput cbInstance = new CheckBoxInput( cbID, Integer.toString( cbValue ) );
	// return cbInstance.render();
	// }
	@Override
	public String render() {
		String html = "";
		String selectorElementName = "instanceSelector_" + getAttribute().getAllowedCls();
		String selectorContainer = "div_" + selectorElementName;

		if ( _toObjOids == null || _relationship == null ) setData( _avPair.getValue() );

		if ( _toObjOids.size() == 0 || getAttribute().isMultiple() ) html += btnAddRelationship( selectorContainer );

		html += "<div id=\"" + selectorContainer + "\" style=\"display:none; \" class=\"popup_big\">";
		html += "<div id=\"" + selectorElementName + "\" style=\"padding:20px;\" >";
		html += "</div><!--end instanceChooser-->";
		html += "<a href=\"#\" onClick=\"Effect.toggle('" + selectorContainer + "', 'appear'); return false;\">close</a>";
		html += "</div>";

		if ( _toObjOids.size() > 0 ) html += instanceTable().render();
		return html;
	}

	@Override
	public void setData( Object data ) {
		if ( data == null || !(data instanceof InstanceRelationship) ) {
			_toObjOids = new ArrayList<Integer>();
			_relationship = new InstanceRelationship( getAttribute(), _avPair.getSeedpodDO().getOid() );
		} else {
			_relationship = (InstanceRelationship)data;
			_toObjOids = _relationship.getTargetOids();
		}
	}

	// private String renderTargetObjectLinks() {
	// String html = "";
	// PManager manager;
	// try {
	// manager = PMFactory.getInstance().createManager();
	// if ( _toObjOids.size() > 0 ) {
	// html += "<ul class=\"objList\">";
	//
	// for ( Integer oid : _toObjOids ) {
	// SeedpodDO obj = manager.createObject( getAttribute().getAllowedCls(), oid );
	// if ( !obj.isPersistent() ) obj.retrieveById();
	// HiddenInput oidInput = new HiddenInput( _widgetID, oid.toString() );
	// html += oidInput.render();
	// html += "<li >" + objectLink( obj ) + "</li>";
	// }
	//
	// html += "</ul>";
	// }
	// } catch (SeedpodException e) {
	// html = e.getMessage();
	// }
	// return html;
	// }

	@Override
	public boolean supportsMultiValueInput() {
		return true;
	}

	@Override
	public void validateWidget() throws InvalidWidgetException {
		if ( getAttribute().isRelationship() ) {
			Object data = getData();
			if ( data != null && !(data instanceof InstanceRelationship) )
				throw new InvalidWidgetException( "(E) Value is  not a relationship to use widget OBJECT_LINK" );
		}
	}

}